package com.hamster.crmpre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hamster.crmpre.config.LoginInterceptor;
import com.hamster.crmpre.mapper.*;
import com.hamster.crmpre.pojo.*;
import com.hamster.crmpre.pojo.dto.ProjectCourseClassTime;
import com.hamster.crmpre.service.CustomerAssetsService;
import com.hamster.crmpre.service.PhoneUserService;
import com.hamster.crmpre.util.JsonUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 转交客户资产的service
 * @author ：Lizhipeng
 * @date ：Created in 2019/12/28 9:31
 * @description： 客户资产服务的实现类
 * @modified By：
 * @version:
 */
@Service
public class CustomerAssetsServiceImpl implements CustomerAssetsService {
    @Autowired
    private HandOverCustomerAssetsMapper handOverCustomerAssetsMapper;
    @Autowired
    private PersonalMessageMapper personalMessageMapper;
    @Autowired
    private CustomerCourseClassMapper customerCourseClassMapper;
    @Autowired
    private CustomerCourseClassTimeMapper customerCourseClassTimeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private PhoneUserService phoneUserService;
    /**
     * 转交客户资产，通过按钮
     * @param id 消息中心的id
     */
    @Transactional
    @Override
    public void handOverPassed(String id) {

        //1.根据消息中心id获取详情的id
        PersonalMessage personalMessage = personalMessageMapper.selectById(id);
        HandOverCustomerAssets handOverCustomerAssets = handOverCustomerAssetsMapper.selectById(personalMessage.getMessageLink());
        //2.修改状态为 同意
        handOverCustomerAssets.setState("1");//同意
        handOverCustomerAssets.setAuditorId(LoginInterceptor.getLoginUser().getUserId());//审核人id
        String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
        handOverCustomerAssets.setAuditorName(userName);//审核人姓名
        Notice notice = new Notice();

            //更新记录
            handOverCustomerAssetsMapper.updateStateById(handOverCustomerAssets);

            //3.对数据进行 删除（原始客户）  和 新增（目标客户）
            //把数据解析出来【存储的数据为 List<CustomerCourseClass> courseList 选中的，其他的不传给后台】
            String content = handOverCustomerAssets.getContent();
            //System.out.println(content);
            List<ProjectCourseClassTime> p = JsonUtils.parseList(content, ProjectCourseClassTime.class);
            //System.out.println(p);
            List<CustomerCourseClass> contentList = new ArrayList<>();
            for (ProjectCourseClassTime projectCourseClassTime : p) {
                contentList.addAll(projectCourseClassTime.getCourseList());
            }

        //判断是转交客户 还是 转成学习卡   0 转给客户    1 转换成学习卡
        if ("0".equals(handOverCustomerAssets.getSelect1())){

            String transferCustomerId = handOverCustomerAssets.getTransferCustomerId();//目标客户的id

            for (CustomerCourseClass customerCourseClass : contentList) {
                //删除原来的
                customerCourseClassMapper.deleteById(customerCourseClass.getId());

                //新增
                customerCourseClass.setId(null);
                customerCourseClass.setCustomerId(transferCustomerId);
                customerCourseClassMapper.insert(customerCourseClass);
                for (CustomerCourseClassTime customerCourseClassTime : customerCourseClass.getTimeList()) {
                    //删除原来的
                    customerCourseClassTimeMapper.deleteById(customerCourseClassTime.getId());

                    //新增
                    customerCourseClassTime.setId(null);
                    customerCourseClassTime.setCourseClassId(customerCourseClass.getId());
                    customerCourseClassTimeMapper.insert(customerCourseClassTime);
                }
            }
            String userName666 = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            String contentMessage ="客户："+handOverCustomerAssets.getCustomerName()+" 转交客户资产给 "+handOverCustomerAssets.getTransferCustomerName()+"。审核人："+userName666 ;
            notice.setContent(contentMessage);
        }else if (("1".equals(handOverCustomerAssets.getSelect1()))){
            //删除原来的
            for (CustomerCourseClass customerCourseClass : contentList) {
                //删除原来的
                customerCourseClassMapper.deleteById(customerCourseClass.getId());

                for (CustomerCourseClassTime customerCourseClassTime : customerCourseClass.getTimeList()) {
                    //删除原来的
                    customerCourseClassTimeMapper.deleteById(customerCourseClassTime.getId());

                }
            }

            //更新记录
            handOverCustomerAssets.setLearningCard("1");//设置学习卡为已转换
            handOverCustomerAssetsMapper.updateById(handOverCustomerAssets);
            String userName666 = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
            String contentMessage = "客户："+handOverCustomerAssets.getCustomerName()+" 转交资产为学习卡。审核人："+userName666 ;
            notice.setContent(contentMessage);

        }

        //4.通过之后给财务发个消息通知
        //通知财务一声

        //String serialize = JsonUtils.serialize(handOverCustomerAssets);
        ;
        noticeMapper.insert(notice);

        PersonalMessage personalMessage1 = new PersonalMessage();
        personalMessage1.setMessageType("通知消息");
        personalMessage1.setSenderId("系统");
        personalMessage1.setSenderName("系统");
        personalMessage1.setMessageLink(notice.getId());
        personalMessage1.setCreateTime(new Date());
        personalMessage1.setState("0");//消息状态 0未读
        personalMessage1.setReceiverId("财务部");
        personalMessage1.setReceiverName("财务部");
        personalMessage1.setDepartment("财务部");
        personalMessageMapper.insert(personalMessage1);



    }

    /**
     * 客户转交资产拒绝 按钮
     * @param id
     */
    @Override
    public void handOverRefuse(String id) {
        //根据消息中心id获取详情的id
        PersonalMessage personalMessage = personalMessageMapper.selectById(id);
        HandOverCustomerAssets handOverCustomerAssets = handOverCustomerAssetsMapper.selectById(personalMessage.getMessageLink());
        //TODO 客户转交资产功能待实现
        handOverCustomerAssets.setState("2");//拒绝
        handOverCustomerAssets.setAuditorId(LoginInterceptor.getLoginUser().getUserId());
        String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
        handOverCustomerAssets.setAuditorName(userName);
        handOverCustomerAssetsMapper.insert(handOverCustomerAssets);

    }

    /**
     * 获取页面课程列表（跟课程明细的区别在于，没有时间筛选）
     * @param customerId 用户id
     * @return
     */
    @Override
    public List<CustomerCourseClass> getCourseDetails(String customerId) {
        QueryWrapper<CustomerCourseClass> customerCourseClassQueryWrapper = new QueryWrapper<>();
        customerCourseClassQueryWrapper.eq("customer_id",customerId);
        List<CustomerCourseClass> courseClassList = customerCourseClassMapper.selectList(customerCourseClassQueryWrapper);

        for (CustomerCourseClass customerCourseClass : courseClassList) {
            QueryWrapper<CustomerCourseClassTime> customerCourseClassTimeQueryWrapper = new QueryWrapper<>();
            customerCourseClassTimeQueryWrapper.eq("course_class_id",customerCourseClass.getId());
            List<CustomerCourseClassTime> customerCourseClassTimes = customerCourseClassTimeMapper.selectList(customerCourseClassTimeQueryWrapper);
            customerCourseClass.setTimeList(customerCourseClassTimes);
        }

        return courseClassList;
    }

    /**
     * 发起转交客户资产  提交按钮 【上级审核】
     * @param handOverCustomerAssets
     */
    @Override
    public void submitCustomerAssets(HandOverCustomerAssets handOverCustomerAssets) {
        handOverCustomerAssets.setDeveloperId(LoginInterceptor.getLoginUser().getUserId());//员工id
        String userName = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
        handOverCustomerAssets.setDeveloperName(userName);//员工姓名
        handOverCustomerAssets.setInputTime(new Date());
        handOverCustomerAssets.setInputUser(userName);
        // 0 转给客户    1 转换成学习卡
        if ("1".equals(handOverCustomerAssets.getSelect1())){ //如果客户选择转成学习卡，这里设置，学习卡未转换，否则为空不用管。
            handOverCustomerAssets.setLearningCard("0");//还未转成学习卡
        }
        handOverCustomerAssets.setState("0");
        handOverCustomerAssets.setDel("0");
        handOverCustomerAssetsMapper.insert(handOverCustomerAssets);//消息詳情已插入

        String linkId = handOverCustomerAssets.getId();
        //因为需要先交给自己的上级，经理或总监。所以查找上级经理或总监的id
        //TODO 查找自己的上级经理或总监，如果自己就是经理或总监咋办？？？？？  待定 等客户改再说
        Employee employee = employeeMapper.selectById(LoginInterceptor.getLoginUser().getUserId());
        Employee superior = employeeMapper.selectById( employee.getSuperiorId());

        PersonalMessage personalMessage = new PersonalMessage();
        //不能没有上级id
        if (superior != null){
            //判断上级领导是否是经理或者总监
            if (superior.getPosition().equals("2")||superior.getPosition().equals("3")){
                personalMessage.setSenderId(LoginInterceptor.getLoginUser().getUserId());
                String userName66 = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
                personalMessage.setSenderName(userName66);
                personalMessage.setReceiverName(superior.getName());//接收人姓名
                personalMessage.setReceiverId(superior.getId());//接收人id
                personalMessage.setState("0");//未讀
                personalMessage.setMessageLink(linkId);
                personalMessage.setMessageType("客户资产转交");
                personalMessage.setCreateTime(new Date());
            }else {//如果不是，那就获得上级的上级，这次肯定是，如果还不是数据就有问题
                Employee superior2 = employeeMapper.selectById(superior.getSuperiorId());
                //判断上级领导是否是经理或者总监
                if (superior2.getPosition().equals("2")||superior2.getPosition().equals("3")) {
                    personalMessage.setSenderId(LoginInterceptor.getLoginUser().getUserId());
                    String userName6 = phoneUserService.queryNameByPhone(LoginInterceptor.getLoginUser().getPhone());
                    personalMessage.setSenderName(userName6);
                    personalMessage.setReceiverName(superior2.getName());//接收人姓名
                    personalMessage.setReceiverId(superior2.getId());//接收人id
                    personalMessage.setState("0");//未讀
                    personalMessage.setMessageLink(linkId);
                    personalMessage.setMessageType("客户资产转交");
                    personalMessage.setCreateTime(new Date());
                }
            }
        }

        personalMessageMapper.insert(personalMessage);

    }

    /**
     * 查询目标客户的select列表
     * @return
     */
    @Override
    public List<Customer> selectCustomer() {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","name","phone");
        return   customerMapper.selectList(queryWrapper);
    }
}
